<!-- model的公共组件：增删改查的弹窗子组件，支持的表单格式有 新增、编辑、查看 -->
<template>
  <Modal
    v-model="drawer.show"
    :width="width"
    :closable="drawer.status == 'read'"
    :mask-closable="false"
    :styles="styles"
  >
    <span slot="header" :style="titleStyle">{{ lang[drawer.status] }}</span>
    <div slot="footer">
      <Button v-if="drawer.status!=='read'" @click="drawer.show = false">{{ $t(`global.cancel`) }}</Button>
      <Button
        type="primary"
        class="ivu-ml"
        @click="ok"
        >{{ drawer.status == 'read' ? $t(`global.close`) : $t(`global.save`) }}</Button
      >
    </div>
    <div v-if="drawer.show && classObject.record" :style="bodyStyle">
      <Form
        ref="_frm"
        :model="classObject.record"
        :label-width="labelWidth"
        :label-position="labelPosition"
        :disabled="drawer.status === 'read'"
      >
        <!-- 基本字段 type className name comments -->
        <Row :gutter="32">
          <Col v-for="item in calcFields" :span="item.span || 12" :key="item.key">
            <FormItem :prop="item.key" :label="item.title" :rules="item.rules" class="aaxx">
              <fieldCell
                :config="{
                  ...item.config,
                  options: item.key==='className' && isInstance ? classNameList : item.config.options 
                }"
                v-model="classObject.record[item.key]"
                @change="change(item.key, $event)"
              />
            </FormItem>
          </Col>
        </Row>
        <Row v-if="hasFeatures && !isInstance && drawer.status !== 'new'" :gutter="32">
          <!-- properties -->
          <Col span="24">
            <Alert style="margin: 0">{{ $t(`model.modelProperties`) }}</Alert>
            <cfgModelProperty
              ref="_features"
              :classObject="classObject"
              :disabled="drawer.status == 'read'"
            />
          </Col>
          <!-- <Col span="24">
            <Alert style="margin: 0">{{ $t(`model.modelStatusProperties`)}}</Alert>
            <cfg-modelStatusProperty :value="classObject.record.statusProperties"/>
          </Col> -->
        </Row>
        <!-- 根据业务需求，配置的自定义表单字段 -->
        <component v-if="additionForm" :is="additionForm" v-model="classObject.record"></component>
        <!-- 实例对应的 model字段列表 -->
        <template v-if="isInstance && drawer.status !== 'new' && hasFeatures">
          <Alert>{{ lang.modelProperties }}</Alert>
          <FormItem v-for="(item, index) in modelFieldList" :key="index" :prop="item.key" :label="item.title">
            <field-cell :config="item.config" v-model="classObject.record.values[item.key]" />
          </FormItem>
        </template>
      </Form>
    </div>
  </Modal>
</template>

<script>
import CfgEditTable from 'public/components/basic/cfgEditTable.vue'
import cfgCell from '../cfg-cell.vue'

let statusTypeOptionsAll = []
for (let i=0; i<15; i++) {
  statusTypeOptionsAll.push({label: `st${i}`, value: `st${i}`,})
}

export default {
  name: "cfgEditModal",
  components: {cfgCell, CfgEditTable},
  data() {
    return {
      general: {
        status: { type: 'Boolean', defaultValue: false },
        name: { type: 'string', defaultValue: "" },
      },
      propInfo: {},
      values: {},
      modelFieldList: []
    }
  },
  methods: {
    change(key, value) {
      if (this.isInstance && key === 'type') {
        this.classObject.record.className = ''
      }
    },
    // 提交添加或修改数据
    ok() {
      if (this.drawer.status === 'read') {
        this.drawer.show = false
        return
      }
      this.$refs._frm.validate(valid => {
        try {
          if (valid) {
            this.$refs._features && this.$refs._features.getValues();
            console.log("file: cfgCrud-modal.vue ok1", valid)
            this.$emit('submit')
            this.$refs._frm.resetFields()
            this.drawer.show = false
          }
        } catch(err) {
          console.log("file: cfgCrud-modal.vue:118  ok  err:", err)
          
        }
      });
    },
    // 动态生成当前实例对应的字段表
    calcModelFields() {
      if (this.isInstance && this.classObject.record && this.classObject.record.className) {
        this.modelFieldList = this.classObject.calcModelFields(this.modelList)
        console.log("file: cfgCrud-modal.vue:127  calcModelFields", this.modelList,)
      }
    },
    getStatusOptions(row, index) {
      let status = this.classObject.record.statusProperties || []
      let res = []
      let _statusTypeOptionsAll = this.tools.lodash.cloneDeep(statusTypeOptionsAll)
      
      _statusTypeOptionsAll.forEach(item => {
        let _index = status.findIndex(vItem => vItem.type === item.value)
        res.push({
          ...item,
          disabled: _index !== -1 && _index !== index
        })
      })
      return res
    }
  },
  props: {
    drawer: {
      default: () => {
        return {
          status: 'edit', // new edit read
          show: false,
        };
      }
    },
    fields: {
      default() {
        return []
      }
    },
    modelList: {
      default() {
        return []
      }
    },
    classObject: {
      default() {
        return null
      }
    },
    collectionObject: {
      default() {
        return null
      }
    },
    defaultType: {
      default() {
        return ''
      }
    },
    width: {
      default: () => {
        return 90;
      }
    },
    titleStyle: {
      default: () => {
        return {}
      }
    },
    modalTitle: {
      default: ''
    },
    hasFeatures: {
      default() {
        return false
      }
    },
    isInstance: {        // 当时是实例管理页面：包含模板的字段列表
      default: false
    },
    additionForm: {
      default() {
        return ''
      }
    },
    styles: {
      default() {
        return {top: '50px', maxWidth: '1200px'}
      }
    },
    bodyStyle: {
      default() {
        return {}
      }
    },
    labelWidth: {
      default() {
        return 120
      }
    },
    labelPosition: {
      default() {
        return 'right'
      }
    },
  },
  watch: {
    'drawer.show'(val) {
      if (val) {
        this.calcModelFields()
      }
    }
  },
  computed: {
    classNameList() {
      if(this.modelList) {
        let curList = this.classObject.record.type ? this.modelList.filter(item => item.type === this.classObject.record.type) : []
        return curList.map(item => {
          return {label: item.className, value: item.className, nodeId: item.nodeId}
        })
      } else {
        return []
      }
    },
    calcFields() {
      if (this.drawer.status === 'edit') {
        let res = this.fields.map(item => ({
            ...item,
            config: Object.assign({}, item.config, item.editConfig || {})
        }))
        return res;
      } else {
        return this.fields
      }
    },
    statusColumns() {
      return [
          {
            key: 'type',
            title: this.lang.type,
            slot: 'slotCustom1',
          },
          {
            key: 'name',
            title: this.lang.name,
            elementName: 'fieldCell',
            props: { config: { type: 'text', clearable: true } }
          },
          {
            key: 'defaultValue',
            title: this.lang.defaultValue,
            elementName: 'fieldCell',
            props: { config: { type: 'text', clearable: true } }
          },
          {
            key: 'comments',
            title: this.lang.comments,
            elementName: 'fieldCell',
            props: { config: { type: 'text', clearable: true } }
          },
          { slot: 'operation', }
      ]
    },
    lang() {
      return {
        "en-US": {
          edit: 'edit',
          new: 'new',
          read: 'read',
          action: 'action',
          submit: 'submit',
          type: 'type',
          typePlaceholder: 'Please select type',
          className: 'className',
          classNamePlaceholder: 'Please enter class name',
          version: 'version',
          versionPlaceholder: 'Please enter version',
          published: 'published',
          comments: 'comments',
          commentsPlaceholder: 'Please enter comments',
          typeRuleMsg: 'Please select property type',
          classNameRuleMsg: 'Please enter class name',
          commentsPlaceholder: 'Please enter comments',
          modelProperties: 'Model Attribute Configuration',
        },
        "zh-CN": {
          edit: '编辑',
          new: '添加',
          read: '查看',
          action: '操作',
          submit: '提交',
          type: '所属类型',
          typePlaceholder: '请选择所属类型',
          className: '模型类名',
          classNamePlaceholder: '请输入模型类名',
          version: '版本号',
          versionPlaceholder: '请输入版本号',
          published: '是否发布',
          comments: '说明',
          commentsPlaceholder: '请输入描述信息',
          typeRuleMsg: '请选择所属类型',
          classNameRuleMsg: '请输入模型类名',
          modelProperties: '基本属性配置',
          modelStatusProperties: '状态属性配置',
          // statusProperties
          name: '名称',
          type: '类型',
          defaultValue: '默认值',
          comments: '备注',
        },
      }[this.G_Locale]
    },
  },
}
</script>
